#pragma once
#include <iostream>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"


class TcpSocket
{
    static const int defaultbacklog = 32;

public:
    TcpSocket() : _fd(-1) {}

    void ListenSocket(uint16_t port)
    {
        // 创建监听sock
        _fd = socket(AF_INET, SOCK_STREAM, 0);
        if (_fd < 0)
        {
            LOG(Abnormal, "create listen sock error\n");
            exit(1);
        }


        int opt = 1;
        setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_fd, (struct sockaddr *)(&addr), sizeof(addr));
        if (n < 0)
        {
            LOG(Abnormal, "bind listen sock error\n");
            exit(1);
        }

        n = listen(_fd, defaultbacklog);
        if (n < 0)
        {
            LOG(Abnormal, "listen listen sock error\n");
            exit(1);
        }
    }

    int GetSockFd()
    {
        return _fd;
    }

    ~TcpSocket() {}

private:
    int _fd;
};